use crate::Token;
use crate::TokenKind;

#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Span {
    start: usize,
    end: usize,
}

impl Span {
    fn new(start:usize, end:usize) -> Self {
        Span {
            start,
            end,
        }
    }

    pub fn get_start(&self) -> usize {
        self.start
    }

    pub fn get_end(&self) -> usize {
        self.end
    }
}

#[derive(Debug, PartialEq)]
pub enum AstNode {
    Module(String, Vec<AstNode>, Span),
    UseStatement(String, Span),
    ExternStatement(String, Span),
    StructDef(String, Vec<(String, String)>, Span), // (field_name, type)
    ImplBlock(String, Vec<FunctionDef>, Span),
    ConstDef(String, String, String, Span), // (name, type, value)
    StaticVarDef(String, String, String, Span), // (name, type, value)
    FunctionDef(String, Vec<(String, String)>, Box<AstNode>, Option<String>, Span), // (name, params, body, return type)
    Block(Vec<AstNode>, Span),
    Statement(Expression, Span),
    Expr(Expression, Span),
    IfStatement(Expression, Box<AstNode>, Span),
    ElseStatement(Expression, Box<AstNode>, Span),
    WhileStatement(Expression, Box<AstNode>, Span),
    ForStatement(Expression, Box<AstNode>, Span),
    LoopStatement(Expression, Box<AstNode>, Span),
    Return(Expression, Span),
    TraitBlock(String, Vec<FunctionDef>, Span),
    Attribute(String, Span),
    LetStatement(String, Span),
    TypeDef(String, String, String, Span),
    EnumDef(String, Vec<String>, Span),
    MacroRules(String, Box<AstNode>, Span),
    Invalid(String, Span),
}

#[derive(Debug, PartialEq)]
pub struct FunctionDef {
    name: String,
    params: Vec<(String, String)>,  // Parameter list, including parameter names and types
    body: Box<AstNode>,             // Function body, containing a series of AST nodes
    ret_type: Option<String>,
    span: Span,
}

#[derive(Debug, PartialEq)]
pub struct Program {
    pub items: Vec<AstNode>,
}

#[derive(Debug, PartialEq)]
pub enum Expression {
    Variable(Option<String>, Span),
    Number(i32, Span),
    Boolean(bool, Span),
    Comment(String, Span),
    Comma(String, Span),
    Dot(String, Span),
    OpenParen(String, Span),
    CloseParen(String, Span),
    OpenBrace(String, Span),
    CloseBrace(String, Span),
    OpenBracket(String, Span),
    CloseBracket(String, Span),
    Question(String, Span),
    Colon(String, Span),
    Dollar(String, Span),
    Eq(String, Span),
    Bang(String, Span),
    Lt(String, Span),
    Gt(String, Span),
    Minus(String, Span),
    And(String, Span),
    Or(String, Span),
    Plus(String, Span),
    Star(String, Span),
    Slash(String, Span),
    Caret(String, Span),
    Percent(String, Span),
    Semi(String, Span),
    If(String, Span),
    Else(String, Span),
    While(String, Span),
    For(String, Span),
    Loop(String, Span),
    Return(String, Span),
    Pub(String, Span),
    Unsafe(String, Span),
    Lifetime(String, Span),
    Fn(String, Span),
    Pound(String, Span),
    Unknown,
    // Other expression types ...
}

//pub struct Parser<'a>
pub struct Parser<'a> {
    tokens: Vec<Token>,
    current: usize,
    input: &'a str,
}

//impl<'a> Parser<'a> {
impl<'a> Parser<'a> {
    pub fn new(tokens: Vec<Token>, input: &'a str) -> Self {
        Parser { tokens, current: 0, input }
    }

    pub fn parse_program(&mut self) -> Program {
        let mut items = Vec::new();
        while !self.at_end() {
            let item = self.parse_item();
            match item {
                AstNode::Invalid(_, _span) => {
                    //println!("Ignore invalid item[{}-{}]!", span.start, span.end)
                },
                _ => {
                    //println!("{:?}", item);
                    items.push(item);
                },
            }
        }
        Program { items }
    }

    fn parse_item(&mut self) -> AstNode {
        //println!("Parse item:{}, {:?}", self.current, self.peek());
        //let modifiers = self.get_modifiers();
        // Parse possible pub and unsafe keywords
        let mut modifiers = Vec::new();
        //while self.check(TokenKind::Pub) || self.check(TokenKind::Unsafe) || self.check(TokenKind::Whitespace){
        //    if self.check(TokenKind::Whitespace) {
        //        self.advance();
        //        continue
        //    }
        //    let modifier_token = self.advance();
        //    modifiers.push(modifier_token);
        //}
        match self.peek().kind {
            TokenKind::Fn => self.parse_function(modifiers),
            TokenKind::Struct => self.parse_struct(),
            TokenKind::Impl => self.parse_impl(),
            TokenKind::Const => self.parse_const(),
            TokenKind::Static => self.parse_static(),
            TokenKind::Mod => self.parse_module(),
            TokenKind::Use => self.parse_use(),
            TokenKind::Extern => self.parse_extern(),
            TokenKind::Trait => self.parse_trait(),
            TokenKind::Pound => self.parse_attribute(),
            TokenKind::Type => self.parse_typedef(),
            TokenKind::Enum => self.parse_enum(),
            TokenKind::Ident => {
                let token = self.advance();
                if let Some(token_name) = &token.lexeme {
                    if token_name == "macro_rules" {
                        return self.parse_macro_rules();
                    }
                }
                let span = Span::new(token.start, token.end);
                AstNode::Invalid(format!("Unexpected token: {:?}", token.kind), span)
            },
            //TokenKind::Statement => self.parse_statement(),
            _ => {
                let token = self.advance();
                if token.kind == TokenKind::Pub || token.kind == TokenKind::Unsafe {
                    modifiers.push(token);
                }
                let span = Span::new(token.start, token.end);
                AstNode::Invalid(format!("Unexpected token: {:?}", token.kind), span)
            }
        }
    }

    fn get_modifiers(&mut self) -> Vec<&Token>{
        // Parse possible pub and unsafe keywords
        let mut modifiers = Vec::new();
        let mut kind = self.peek().kind;
        while kind == TokenKind::Pub || kind == TokenKind::Unsafe || 
            kind == TokenKind::Whitespace {
            //let modifier_token = self.advance();
            //kind = modifier_token.kind;
            //if modifier_token.kind != TokenKind::Whitespace {
            //     modifiers.push(modifier_token);
            //}
        }
        modifiers
    }

    pub fn parse_function(&mut self, modifiers: Vec<&Token>) -> AstNode {
        // Assuming the current token is `fn`
        let mut start = self.peek().start;
        let mut flag = false;
        if modifiers.len() > 0 {
            let token = modifiers[0];
            start = token.start;

        }
        self.expect(TokenKind::Fn);  // Consume `fn`

        self.skip_whitespace();
        let mut name;
        if self.check(TokenKind::OpenParen) {
            name = "anonymous".to_string();
        } else{
            name = self.parse_identifier();  // Parsing function name
        }
        //println!("func name:{}", name);
        self.skip_whitespace();
        if self.check(TokenKind::Lt) {
            self.parse_generic_params();  // Parse generic parameters after function name
        }
        self.expect(TokenKind::OpenParen);  // consume `(`

        let params = if !self.check(TokenKind::CloseParen) {
            self.parse_parameters()  // Parsing parmeters
        } else {
            Vec::new()  // No parameters
        };

        self.expect(TokenKind::CloseParen);  // consume `)`
        self.skip_whitespace();

        // Parse return type
        let return_type = if self.check_arrow() {
            self.expect_arrow();  // Consume `->`
            self.skip_whitespace();  // Skip whitespace
            let return_type = self.parse_complex_type();
            //while !self.check(TokenKind::OpenBrace) {
            //    self.advance();
            //}
            self.skip_whitespace();
            Some(return_type)  // Parse return type
        } else {
            None  // No return type
        };
         
        self.skip_whitespace();
        //println!("parse block");
        let body = self.parse_block();  // Parsing body
        //println!("fn body:{:?}", body);
        match body {
            AstNode::Invalid(_, _) => {
                //let span = Span::new(0, 0);
                //return AstNode::Invalid("Invalid function body".to_string(), span);
                flag = true;
            },
            _ => {
            },
        }
        let end = self.previous().end;
        let span = Span::new(start, end);
        if flag {
            AstNode::Invalid("Invalid function".to_string(), span)
        } else {
            AstNode::FunctionDef(name, params, Box::new(body), return_type, span)
        }
    }

    fn parse_generic_params(&mut self) {
        self.expect(TokenKind::Lt);  // Consume '<'
        while !self.check(TokenKind::Gt) || self.previous().kind == TokenKind::Minus {
            // Parse each generic parameter
            //self.parse_generic_param();
            //if self.check(TokenKind::Comma) {
            //    self.advance();  // Consume ','
            //}
            if self.check(TokenKind::Lt) {
                self.parse_generic_params();
            } else {
                self.advance();
            }
        }
        self.expect(TokenKind::Gt);  // Consume '>'
    }

    fn parse_generic_param(&mut self) {
        // Implementation depends on your generic parameter syntax
        // This could include parsing lifetimes or type constraints
    }
    
    // Used to parse basic types
    fn parse_basic_type(&mut self) -> String {
        let mut typename = String::new();
        if let Some(type_name) = &self.peek().lexeme {
            let name = &type_name;
            for char in name.chars(){
                if char.is_alphanumeric() || char == ':' || 
                    char == '<' || char == '>' || char == ',' ||
                    char == '_' {
                    //typename.push(self.advance().lexeme.unwrap());
                    typename.push(char);
                } else {
                    break;
                }
            }
        }
        //println!("Basic type:{} {:?}", typename, self.peek().lexeme);
        //self.advance();
        typename
    }
    
    fn check_lifetime(&self) -> bool {
        self.peek().kind.is_lifetime()
    }

    fn parse_complex_type(&mut self) -> String {
        // A complex type parser that handles references, lifetimes, generics, and more
        // For simplicity, just return a placeholder string here
        let mut type_str = String::new();

        if self.check(TokenKind::And) {
            // Consume '&'
            self.advance();
            type_str.push('&');

            // Optional lifetime
            if self.check_lifetime() {
                //type_str.push_str(&self.advance().lexeme.unwrap());
                if let Some(lt) = &self.advance().lexeme {
                    type_str.push_str(&lt.clone());
                }
                self.skip_whitespace();  // Skip any whitespace after the lifetime
            }
        } else if self.check(TokenKind::Star) {
            self.advance();
            type_str.push('*');
        }
        let mut pairs = Vec::new();
        loop {
            // Append the basic type part
            match self.peek().kind {
                TokenKind::Ident => {
                    type_str.push_str(&self.parse_basic_type());
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Const => {
                    type_str.push_str("const");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Colon => {
                    type_str.push_str(":");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Lt => {
                    type_str.push_str("<");
                    pairs.push("<");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Gt => {
                    if pairs.is_empty() && !type_str.contains("fn(") {
                        break;
                    }
                    type_str.push_str(">");
                    pairs.pop(); 
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::OpenBracket => {
                    type_str.push_str("[");
                    pairs.push("[");
                    self.advance();
                    self.skip_whitespace();
                }
                TokenKind::CloseBracket => {
                    if pairs.is_empty() {
                        break;
                    }
                    type_str.push_str("]");
                    pairs.pop();
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::OpenParen => {
                    type_str.push_str("(");
                    pairs.push("(");
                    self.advance();
                    self.skip_whitespace();
                }
                TokenKind::CloseParen => {
                    if !pairs.is_empty() {
                        pairs.pop();
                    } else {
                        break;
                    }
                    type_str.push_str(")");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Minus => {
                    type_str.push_str("-");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Plus => {
                    type_str.push_str("+");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Semi => {
                    type_str.push_str(";");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Literal {kind, suffix_start} => {
                    type_str.push_str("Literal");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Impl => {
                    type_str.push_str("impl");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Fn => {
                    type_str.push_str("fn");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Lifetime {starts_with_number} => {
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Star => {
                    type_str.push('*');
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::And => {
                    type_str.push('&');
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Extern => {
                    type_str.push_str("extern");
                    self.advance();
                    self.skip_whitespace();
                },
                _ => {
                    if pairs.is_empty() {
                        break;
                    } else {
                        self.advance();
                        continue;
                    }
                },
            }
        }
        //println!("complex type:{}", type_str); 
        type_str
    }

    fn parse_identifier(&mut self) -> String {
        match self.advance().kind {
            TokenKind::Ident => self.previous().lexeme.clone().expect("Identifier"),
            TokenKind::RawIdent => self.previous().lexeme.clone().expect("Identifier"),
            _ => {
                //eprintln!("Unexpected token:{:?}", self.previous());
                //panic!("Expected identifier")
                "".to_string()
            },
        }
    }

    fn parse_parameters(&mut self) -> Vec<(String, String)> {
        let mut params = Vec::new();
        loop {
            let mut param_name = String::new();
            self.skip_whitespace();
            if self.check(TokenKind::And) {
                // Consume '&'
                self.advance();
                param_name.push('&');

                // Optional lifetime
                if self.check_lifetime() {
                    //type_str.push_str(&self.advance().lexeme.unwrap());
                    if let Some(lt) = &self.advance().lexeme {
                        param_name.push_str(&lt.clone());
                    }
                    self.skip_whitespace();  // Skip any whitespace after the lifetime
                }
            } else if self.check(TokenKind::CloseParen) {
                break;
            }
            param_name.push_str(&self.parse_identifier());  // parse parameter name
            if self.check(TokenKind::Comma) {
                self.advance();
                params.push((param_name, String::new()));
                self.skip_whitespace();
                continue;
            }
            self.skip_whitespace();
            //println!("{}", param_name);
            while !(self.check(TokenKind::Colon) || self.check(TokenKind::CloseParen)) {
                 if self.check(TokenKind::Comma) {
                     break;
                 }
                 let param_part = self.parse_identifier();
                 param_name += &param_part;
                 self.skip_whitespace();
            }
            if self.check(TokenKind::Comma) {
                params.push((param_name, String::new()));
                self.advance();
                self.skip_whitespace();
                continue;
            }
            if !(self.peek().kind == TokenKind::CloseParen) {
                self.expect(TokenKind::Colon);  // consume `:`
            }
            self.skip_whitespace();
            let type_name = self.parse_complex_type();  // Parse type
            //println!("type name:{}", type_name);
            params.push((param_name, type_name));
            self.skip_whitespace();
            //println!("{:?}", self.peek());
            if self.check(TokenKind::Comma) {
                self.advance();  // consume `,`
                //self.skip_whitespace();
            } else {
                break;
            }
        }
        //println!("Parameters:{:?}", params);
        params
    }

    fn parse_type(&mut self) -> String {
        // assuming the type is a single identifier
        self.parse_identifier()
    }

    fn parse_block(&mut self) -> AstNode {
        let start = self.peek().start;
        if self.peek().kind != TokenKind::OpenBrace {
            let span = Span::new(0, 0);
            return AstNode::Invalid("Invalid block".to_string(), span);
        }
        //println!("begin block!");
        self.expect(TokenKind::OpenBrace);  // consume `{`
        let mut nodes = Vec::new();
        while !self.check(TokenKind::CloseBrace) {
            self.skip_whitespace();
            let node = self.parse_statement();
            match node {
                AstNode::Invalid(_, span) => {
                    return node;
                }
                _ => {}
            }
            nodes.push(node);
            self.skip_whitespace();
            //self.advance();
        }
        let end = self.peek().end;
        let span = Span::new(start, end);
        self.expect(TokenKind::CloseBrace);  // consume `}`
        //println!("Finish block!");
        AstNode::Block(nodes, span)
    }

    fn parse_statement(&mut self) -> AstNode {
        //println!("statement:{:?}", self.peek());
        match self.peek().kind {
            TokenKind::OpenBrace => self.parse_block(),  // Parse block
            TokenKind::If => self.parse_if_statement(), // Parse if
            TokenKind::Else => self.parse_else_statement(), // Parse else
            TokenKind::While => self.parse_while_statement(), // Parse while 
            TokenKind::For => self.parse_for_statement(), // Parse for
            TokenKind::Loop => self.parse_loop_statement(), // Parse loop
            TokenKind::Return => self.parse_return_statement(), // Parse return
            TokenKind::Use => self.parse_use(),
            TokenKind::Const => self.parse_const(),
            TokenKind::Static => self.parse_static(),
            TokenKind::Fn => self.parse_function(Vec::new()),
            TokenKind::Let => self.parse_let(),
            TokenKind::Pound => self.parse_attribute(),
            TokenKind::Struct => self.parse_struct(),
            _ => self.parse_expression_or_simple_statement(),
        }
    }

    fn parse_expression_or_simple_statement(&mut self) -> AstNode {
        let start = self.peek().start;
        let expr = self.parse_expression();
        match expr {
            Expression::Unknown => {
                let span = Span::new(start, self.peek().end);
                return AstNode::Invalid("Invalid expression!".to_string(), span);
            }
            _ => {}
        }
        if self.check(TokenKind::Semi) {
            let end = self.peek().end;
            let span = Span::new(start, end);
            self.advance(); // consume ';'
            AstNode::Statement(expr, span)
        } else {
            let end = self.peek().end;
            let span = Span::new(start, end);
            // assume this is a return value expression
            AstNode::Expr(expr, span)
        }
    }

    fn parse_expression(&mut self) -> Expression {
        let start = self.peek().start;
        // assuming that the expression is only composed of a single identifier or literal value
        let mut token = self.peek();
        if !self.check(TokenKind::Fn) && !self.check(TokenKind::CloseBrace) {
            token = self.advance();
        } 
        let end = token.end;
        let span = Span::new(start, end);
        //println!("expression token:{:?}", token);
        match token.kind {
            TokenKind::Ident => {
                let name = token.lexeme.clone().expect("Identifier"); 
                Expression::Variable(Some(name), span)
            },
            TokenKind::Literal{kind, suffix_start} => {
                Expression::Number(0, span)
            },
            TokenKind::LineComment {doc_style} => {
                Expression::Comment("LineComment".to_string(), span)
            },
            TokenKind::BlockComment {doc_style, terminated} => {
                Expression::Comment("BlockComment".to_string(), span)
            },
            TokenKind::Comma => {
                Expression::Comma(",".to_string(), span)
            }
            TokenKind::Dot => {
                Expression::Dot(".".to_string(), span)
            }
            TokenKind::OpenParen => {
                //let mut path = self.collect_until(TokenKind::CloseParen);
                let mut path = self.collect_paren_pair();
                path.push_str(")");
                self.advance();
                Expression::OpenParen(path, span)
            }
            TokenKind::CloseParen => {
                Expression::CloseParen(")".to_string(), span)
            }
            TokenKind::OpenBrace => {
                Expression::OpenBrace("{".to_string(), span)
            }
            TokenKind::CloseBrace => {
                Expression::CloseBrace("}".to_string(), span)
            }
            TokenKind::OpenBracket => {
                let mut path = self.collect_until(TokenKind::CloseBracket);
                path.push_str("]");
                Expression::OpenBracket(path, span)
            }
            TokenKind::CloseBracket => {
                Expression::CloseBracket("]".to_string(), span)
            }
            TokenKind::Question => {
                Expression::Question("?".to_string(), span)
            }
            TokenKind::Colon => {
                Expression::Colon(":".to_string(), span)
            }
            TokenKind::Dollar => {
                Expression::Dollar("$".to_string(), span)
            }
            TokenKind::Eq => {
                Expression::Eq("=".to_string(), span)
            }
            TokenKind::Bang => {
                Expression::Bang("!".to_string(), span)
            }
            TokenKind::Lt => {
                Expression::Lt("<".to_string(), span)
            }
            TokenKind::Gt => {
                Expression::Gt(">".to_string(), span)
            }
            TokenKind::Minus => {
                Expression::Minus("-".to_string(), span)
            }
            TokenKind::And => {
                Expression::And("&".to_string(), span)
            }
            TokenKind::Or => {
                Expression::Or("|".to_string(), span)
            }
            TokenKind::Plus => {
                Expression::Plus("+".to_string(), span)
            }
            TokenKind::Star => {
                Expression::Star("*".to_string(), span)
            }
            TokenKind::Slash => {
                Expression::Slash("/".to_string(), span)
            }
            TokenKind::Caret => {
                Expression::Caret("^".to_string(), span)
            }
            TokenKind::Percent => {
                Expression::Percent("%".to_string(), span)
            }
            TokenKind::Semi => {
                Expression::Semi(";".to_string(), span)
            }
            TokenKind::If => {
                Expression::If("if".to_string(), span)
            }
            TokenKind::While => {
                Expression::While("while".to_string(), span)
            }
            TokenKind::For => {
                Expression::For("for".to_string(), span)
            }
            TokenKind::Loop => {
                Expression::Loop("loop".to_string(), span)
            }
            TokenKind::Return => {
                Expression::Return("return".to_string(), span)
            }
            TokenKind::Pub => {
                Expression::Pub("pub".to_string(), span)
            }
            TokenKind::Unsafe => {
                Expression::Unsafe("unsafe".to_string(), span)
            }
            TokenKind::Lifetime {starts_with_number} => {
                Expression::Lifetime("lifetime".to_string(), span)
            }
            TokenKind::Fn => {
                let modifiers = Vec::new();
                let _function_node = self.parse_function(modifiers);
                Expression::Fn("nested function".to_string(), span)
            }
            TokenKind::Unknown => {
                Expression::Unknown
            }
            //TokenKind::Pound => {
            //    Expression::Pound("#".to_string(), span)
            //}
            //TokenKind::CloseBrace => {
            //}
            _ => panic!("Unexpected token in expression parsing: {:?}", token),
        }
    }

    fn parse_return_statement(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::Return); // consume `return`
        self.skip_whitespace();
        let path = self.collect_statement(); // Parse expression
        //println!("return:{:?} {}", self.peek(), path);
        if path.is_empty() {
            let span = Span::new(start, self.peek().end);
            return AstNode::Invalid("Invalid return statement!".to_string(), span);
        }
        let end = self.peek().end;
        let span = Span::new(start, end);
        let expr = Expression::Return(path, span);
        if self.check(TokenKind::Semi) {
            self.advance(); // consume `;`
            AstNode::Return(expr, span)
        } else {
            //AstNode::Invalid("Invalid return statement!".to_string(), span)
            // There is no ";" after the return
            AstNode::Return(expr, span)
        }
    }

    // Parse struct definition
    fn parse_struct(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::Struct);  // Consume `struct`
        self.skip_whitespace();  // skip whitespace

        if !self.check(TokenKind::Ident) {
            let span = Span::new(start, self.peek().end);
            return AstNode::Invalid("Invalid struct!".to_string(), span);
        }
        let struct_name = self.parse_identifier();  // Parse name
        self.skip_whitespace();
        //println!("struct name:{}", struct_name);
        if self.check(TokenKind::Lt) {
            self.parse_generic_params();
            self.skip_whitespace();
        }
        if !self.check(TokenKind::OpenBrace) {
            let span = Span::new(start, self.peek().end);
            return AstNode::Invalid("Invalid struct!".to_string(), span);
        }
        self.expect(TokenKind::OpenBrace);  // consume `{`
        let mut members = Vec::new();

        while !self.check(TokenKind::CloseBrace) && !self.at_end() {
            self.skip_whitespace();
            self.skip_comment();
            let field_name = self.parse_identifier();  // Parse field name
            if field_name.is_empty() {
                continue
            }
            //println!("field name:{}", field_name);
            self.skip_whitespace();
            self.expect(TokenKind::Colon);  // consume `:`
            self.skip_whitespace();
            let field_type = self.parse_complex_type();  // Parse field type
            //println!("field type:{}", field_type);
            members.push((field_name, field_type));
            //self.advance();
            
            if self.check(TokenKind::Comma) {
                self.advance();  // Consume `,`
            }
            self.skip_whitespace();
            self.skip_comment();            
            self.skip_whitespace();
        }
        let end = self.peek().end;
        self.expect(TokenKind::CloseBrace);  // Consume `}`
        let span = Span::new(start, end);
        AstNode::StructDef(struct_name, members, span)
        //AstNode::StructDef(String::new(), Vec::new())
    }

    // ImplBlock(String, Vec<FunctionDef>),
    fn parse_impl(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::Impl);  // Consume `impl`
        self.skip_whitespace();

        let type_name = self.parse_identifier();  // Parse type
        //println!("Parsing impl:{}", type_name);
        self.skip_whitespace();
        while !self.check(TokenKind::OpenBrace) {
            if self.check(TokenKind::Colon) || self.check(TokenKind::Ident) || 
                self.check(TokenKind::For) || self.check(TokenKind::Whitespace){
                self.advance();
            } else if self.check(TokenKind::Lt) {
                self.parse_generic_params();
            } else {
                let span = Span::new(start, self.peek().end);
                return AstNode::Invalid("Invalid impl".to_string(), span);
                //panic!("Invalid token in impl name {:?}.", self.peek());
            }
        }
        self.expect(TokenKind::OpenBrace);  // Consume `{`
        let mut methods = Vec::new();

        while !self.check(TokenKind::CloseBrace) && !self.at_end() {
            self.skip_whitespace();
            //let modifiers = self.get_modifiers(); 
            if self.check(TokenKind::Fn) {
                //methods.push(self.parse_function());
                if let AstNode::FunctionDef(name, params, body, ret_type, span) = self.parse_function(Vec::new()) {
                    methods.push(FunctionDef { name, params, body, ret_type, span });
                }
            } else {
                // Skip unknown token or log an error
                self.advance();
            }
            self.skip_whitespace();
        }
        let end = self.peek().end;
        self.expect(TokenKind::CloseBrace);  // Consume `}`
        let span = Span::new(start, end);
        AstNode::ImplBlock(type_name, methods, span)
        //AstNode::ImplBlock(String::new(), Vec::new())
    }

    // TraitBlock(String, Vec<AstNode>),
    fn parse_trait(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::Trait);  // Consume `trait`
        self.skip_whitespace();

        let type_name = self.parse_identifier();  // Parse type name
        //println!("Parsing impl:{}", type_name);
        self.skip_whitespace();
        while !self.check(TokenKind::OpenBrace) {
            if self.check(TokenKind::Ident) || self.check(TokenKind::Whitespace){
                self.advance();
            } else if self.check(TokenKind::Lt) {
                self.parse_generic_params();
            } else {
                let span = Span::new(start, self.peek().end);
                return AstNode::Invalid("Invalid trait!".to_string(), span);
                //panic!("Invalid token in impl name {:?}.", self.peek());
            }
        }
        self.expect(TokenKind::OpenBrace);  // Consume `{`
        let mut methods = Vec::new();

        while !self.check(TokenKind::CloseBrace) && !self.at_end() {
            self.skip_whitespace();
            //let modifiers = self.get_modifiers(); 
            if self.check(TokenKind::Fn) {
                //methods.push(self.parse_function());
                if let AstNode::FunctionDef(name, params, body, ret_type, span) = self.parse_function(Vec::new()) {
                    methods.push(FunctionDef { name, params, body, ret_type, span });
                }
            } else {
                // Skip unknown token or log an error
                self.advance();
            }
            self.skip_whitespace();
        }
        let end = self.peek().end;
        self.expect(TokenKind::CloseBrace);  // Consume `}`
        let span = Span::new(start, end);
        AstNode::TraitBlock(type_name, methods, span)
        //AstNode::ImplBlock(String::new(), Vec::new())
    }

    // ConstDef(String, String, String), // (name, type, value)
    fn parse_const(&mut self) -> AstNode {
        let start = self.peek().start;
        //let st = self.collect_until(TokenKind::Semi);
        let st = self.collect_statement();
        let end = self.peek().end;
        let span = Span::new(start, end);
        if !st.is_empty() && self.peek().kind == TokenKind::Semi {
            self.advance();
            AstNode::ConstDef(st, String::new(), String::new(), span)
        } else {
            AstNode::Invalid("Not valid const statement!".to_string(), span)
        }
    }

    // StaticVarDef(String, String, String), // (name, type, value)
    fn parse_static(&mut self) -> AstNode {
        //AstNode::StaticVarDef(String::new(), String::new(), String::new())
        let start = self.peek().start;
        self.expect(TokenKind::Static);  // Consume `static`
        self.skip_whitespace();  // Skip any whitespace

        //let name = self.parse_identifier();  // Parse the variable name
        //self.skip_whitespace();  // Skip whitespace

        //self.expect(TokenKind::Colon);  // Consume `:`
        //self.skip_whitespace();  // Skip whitespace

        //let var_type = self.parse_type();  // Parse the type of the variable
        //self.skip_whitespace();  // Skip whitespace

        //self.expect(TokenKind::Eq);  // Consume `=`
        //self.skip_whitespace();  // Skip whitespace

        let name = String::new();
        let var_type = String::new();
        //let value = self.collect_until(TokenKind::Semi);  // Parse the initialization expression
        let value = self.collect_statement();  // Parse the initialization expression
        let end = self.peek().end;
        //self.expect(TokenKind::Semi);  // Consume `;` ending the declaration
        let span = Span::new(start, end);
        if !value.is_empty() && self.peek().kind == TokenKind::Semi {
            self.advance();
            AstNode::StaticVarDef(name, var_type, value, span)
        } else {
            AstNode::Invalid("Not valid static statement!".to_string(), span)
        }
    }

    // Module(String, Vec<AstNode>),
    fn parse_module(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::Mod);  // Consume `mod`
        self.skip_whitespace();  // Skip any whitespace

        let name = self.parse_identifier();  // Parse the variable name
        self.skip_whitespace();  // Skip whitespace
        if !self.check(TokenKind::OpenBrace) {
            let span = Span::new(start, self.peek().end);
            return AstNode::Invalid("Invalid mod!".to_string(), span);
        }
        self.expect(TokenKind::OpenBrace);  // Consume `{`
        let mut items = Vec::new();

        while !self.check(TokenKind::CloseBrace) && !self.at_end() {
            self.skip_whitespace();
            let item = self.parse_item();
            items.push(item);
            self.skip_whitespace();
        }
        let end = self.peek().end;
        self.expect(TokenKind::CloseBrace);  // Consume `}`
        let span = Span::new(start, end);

        AstNode::Module(name, items, span)
        //AstNode::Module(String::new(), Vec::new())
    }

    fn parse_while_statement(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::While);  // Consume `while`
        let value = self.collect_until(TokenKind::OpenBrace);
        let stmts = self.parse_block(); 
        let span = Span::new(start, self.previous().end);
        if value.is_empty() && self.previous().kind != TokenKind::CloseBrace {
            return AstNode::Invalid("Invalid while!".to_string(), span);
        }
        AstNode::WhileStatement(Expression::While("while".to_string(), span.clone()), Box::new(stmts), span)
    }

    fn parse_if_statement(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::If);  // Consume `if`
        while !self.check(TokenKind::OpenBrace) && !self.check(TokenKind::Comma) {
            self.advance();
        }
        if self.check(TokenKind::OpenBrace) {
            let stmts = self.parse_block(); 
            let span = Span::new(start, self.previous().end);
            if self.previous().kind != TokenKind::CloseBrace {
                //println!("previous:{:?}", self.previous());
                return AstNode::Invalid("Invalid if!".to_string(), span);
            }
            return AstNode::IfStatement(Expression::If("if".to_string(), span.clone()), Box::new(stmts), span);
        }
        let span = Span::new(start, self.peek().end);
        AstNode::IfStatement(Expression::If("if".to_string(), span.clone()), Box::new(AstNode::Expr(Expression::If("if".to_string(), span.clone()), span.clone())), span)
    }

    fn parse_else_statement(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::Else);  // Consume `else`
        self.collect_until(TokenKind::OpenBrace);
        let stmts = self.parse_block(); 
        let span = Span::new(start, self.previous().end);
        if self.previous().kind != TokenKind::CloseBrace {
            return AstNode::Invalid("Invalid else!".to_string(), span);
        }
        AstNode::ElseStatement(Expression::Else("else".to_string(), span.clone()), Box::new(stmts), span)
    }

    fn parse_for_statement(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::For);  // Consume `for`
        let value = self.collect_until(TokenKind::OpenBrace);
        let stmts = self.parse_block();
        let span = Span::new(start, self.previous().end);
        if value.is_empty() && self.previous().kind != TokenKind::CloseBrace {
            return AstNode::Invalid("Invalid for!".to_string(), span);
        }
        AstNode::ForStatement(Expression::For("for".to_string(), span.clone()), Box::new(stmts), span)
    }

    fn parse_loop_statement(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::Loop);  // Consume `loop`
        self.collect_until(TokenKind::OpenBrace);
        let stmts = self.parse_block(); 
        let span = Span::new(start, self.previous().end);
        if self.previous().kind != TokenKind::CloseBrace {
            return AstNode::Invalid("Invalid loop!".to_string(), span);
        }
        AstNode::LoopStatement(Expression::Loop("loop".to_string(), span.clone()), Box::new(stmts), span)
    }

    fn advance(&mut self) -> &Token {
        if !self.at_end() { self.current += 1; }
        self.previous()
    }

    fn peek(&self) -> &Token {
        &self.tokens[self.current]
    }

    fn previous(&self) -> &Token {
        &self.tokens[self.current - 1]
    }

    fn at_end(&self) -> bool {
        if self.current >= self.tokens.len() {
            //println!("{}, {}, {:?}", self.current, self.tokens.len(), self.tokens[self.tokens.len()-1]);
            panic!("Out of bounds!");
        }
        self.peek().kind == TokenKind::Eof
    }

    fn parse_use(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::Use); // Consume `use`
        let path = self.collect_until(TokenKind::Semi);
        let end = self.peek().end;
        let span = Span::new(start, end);
        if !path.is_empty() && self.peek().kind == TokenKind::Semi {
            AstNode::UseStatement(path, span)
        } else {
            AstNode::Invalid("Not valid use statement!".to_string(), span)
        }
    }
    
    fn parse_extern(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::Extern); // Consume `extern`
        let path = self.collect_extern();
        let end = self.peek().end;
        let span = Span::new(start, end);
        //println!("Finish parsing extern!");
        if self.peek().kind == TokenKind::Semi {
            AstNode::ExternStatement(path, span)
        } else {
            AstNode::Invalid("Not valid extern statement!".to_string(), span)
        }
    }
    
    fn parse_attribute(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::Pound); // Consume `#`
        if !self.check(TokenKind::OpenBracket) {
            let span = Span::new(start, self.peek().end);
            return AstNode::Invalid("Invalid attribute".to_string(), span);
        }
        let path = self.collect_until(TokenKind::CloseBracket);
        let end = self.peek().end;
        let span = Span::new(start, end);
        if !path.is_empty() && self.peek().kind == TokenKind::CloseBracket {
            AstNode::Attribute(path, span)
        } else {
            AstNode::Invalid("Invalid attribute!".to_string(), span)
        }
    }

    fn parse_let(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::Let); // Consume `let`
        let path = self.collect_single_block();
        let end = self.peek().end;
        let span = Span::new(start, end);
        if self.peek().kind == TokenKind::Semi {
            AstNode::LetStatement(path, span)
        } else {
            AstNode::Invalid("Not valid Let statement!".to_string(), span)
        }
    }
    
    // TypeDef(String, Span), // (statement, span)
    fn parse_typedef(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::Type);  // Consume `type`
        self.skip_whitespace();  // Skip any whitespace

        //let name = self.parse_identifier();  // Parse the variable name
        //self.skip_whitespace();  // Skip whitespace

        //self.expect(TokenKind::Colon);  // Consume `:`
        //self.skip_whitespace();  // Skip whitespace

        //let var_type = self.parse_type();  // Parse the type of the variable
        //self.skip_whitespace();  // Skip whitespace

        //self.expect(TokenKind::Eq);  // Consume `=`
        //self.skip_whitespace();  // Skip whitespace

        let name = String::new();
        let var_type = String::new();
        let value = self.collect_until(TokenKind::Semi);  // Parse the initialization expression
        let end = self.peek().end;
        //self.expect(TokenKind::Semi);  // Consume `;` ending the declaration
        let span = Span::new(start, end);
        if !value.is_empty() && self.peek().kind == TokenKind::Semi {
            self.advance();
            AstNode::TypeDef(name, var_type, value, span)
        } else {
            AstNode::Invalid("Invalid type statement!".to_string(), span)
        }
    }

    // Parse enumeration
    fn parse_enum(&mut self) -> AstNode {
        let start = self.peek().start;
        self.expect(TokenKind::Enum);  // Consume `enum`
        self.skip_whitespace();

        if !self.check(TokenKind::Ident) {
            let span = Span::new(start, self.peek().end);
            return AstNode::Invalid("Invalid enum!".to_string(), span);
        }
        let enum_name = self.parse_identifier();  // Parse name
        self.skip_whitespace();
        //println!("enum name:{}", enum_name);
        if self.check(TokenKind::Lt) {
            self.parse_generic_params();
            self.skip_whitespace();
        }
        if !self.check(TokenKind::OpenBrace) {
            if self.check(TokenKind::Where) {
                let value = self.collect_until(TokenKind::OpenBrace);
                if value.is_empty() {
                    let span = Span::new(start, self.peek().end);
                    return AstNode::Invalid("Invalid enum!".to_string(), span);
                }
            } else {
                let span = Span::new(start, self.peek().end);
                return AstNode::Invalid("Invalid enum!".to_string(), span);
            }
        }
        self.expect(TokenKind::OpenBrace);  // Consume `{`
        let mut members = Vec::new();

        while !self.check(TokenKind::CloseBrace) && !self.at_end() {
            self.skip_whitespace();
            let field_name = self.parse_field();  // Parse field
            //println!("field name:{}", field_name);
            members.push(field_name);

            if self.check(TokenKind::Comma) {
                self.advance();  // Consume `,`
            }
            self.skip_whitespace();
            self.skip_comment();            
            self.skip_whitespace();
        }
        let end = self.peek().end;
        self.expect(TokenKind::CloseBrace);  // Consume `}`
        let span = Span::new(start, end);
        AstNode::EnumDef(enum_name, members, span)
    }

    fn parse_field(&mut self) -> String {
        let mut field = String::new();
        let mut pairs = Vec::new();
        let mut unknown = false;
        loop {
            //println!("field token:{:?}", self.peek());
            match self.peek().kind {
                TokenKind::Ident => {
                    field.push_str(&self.parse_identifier());
                    self.skip_whitespace();
                },
                TokenKind::Const => {
                    field.push_str("const");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Colon => {
                    field.push_str(":");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Lt => {
                    field.push_str("<");
                    pairs.push("<");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Gt => {
                    if pairs.is_empty() {
                        break;
                    }
                    field.push_str(">");
                    pairs.pop(); 
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::OpenBracket => {
                    field.push_str("[");
                    pairs.push("[");
                    self.advance();
                    self.skip_whitespace();
                }
                TokenKind::CloseBracket => {
                    if pairs.is_empty() {
                        break;
                    }
                    field.push_str("]");
                    pairs.pop();
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::OpenBrace => {
                    field.push_str("{");
                    pairs.push("{");
                    self.advance();
                    self.skip_whitespace();
                }
                TokenKind::CloseBrace => {
                    if pairs.is_empty() {
                        break;
                    }
                    field.push_str("}");
                    pairs.pop();
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::OpenParen => {
                    field.push_str("(");
                    pairs.push("(");
                    self.advance();
                    self.skip_whitespace();
                }
                TokenKind::CloseParen => {
                    if !pairs.is_empty() {
                        pairs.pop();
                    } else {
                        break;
                    }
                    field.push_str(")");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Comma => {
                    if !pairs.is_empty() {
                        field.push_str(",");
                        self.advance();
                        self.skip_whitespace();
                    } else {
                        break;
                    }
                }
                TokenKind::Minus => {
                    field.push_str("-");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Plus => {
                    field.push_str("+");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Semi => {
                    field.push_str(";");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Literal {kind, suffix_start} => {
                    field.push_str("Literal");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Impl => {
                    field.push_str("impl");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Fn => {
                    field.push_str("fn");
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Lifetime {starts_with_number} => {
                    self.advance();
                    self.skip_whitespace();
                },
                TokenKind::Eq => {
                    field.push_str("=");
                    self.advance();
                    self.skip_whitespace();
                }
                _ => {
                    if pairs.is_empty() {
                        if self.check(TokenKind::Unknown){
                            unknown = true;
                        } else {
                            field.push_str(&self.advance().to_string());
                        }
                        break;
                    } else {
                        self.advance();
                        continue;
                    }
                },
            }
        }
        field 
    }

    // Parse macro rules
    fn parse_macro_rules(&mut self) -> AstNode {
        let start = self.previous().start;

        if !self.check(TokenKind::Bang) {
            let span = Span::new(start, self.peek().end);
            return AstNode::Invalid("Invalid macro rules definition!".to_string(), span);
        }
        self.advance(); // skip the `!`
        self.skip_whitespace();
        let macro_name = self.parse_identifier();  // Parse name
        self.skip_whitespace();
        //println!("macro name:{}", macro_name);
        
        if !self.check(TokenKind::OpenBrace) {  // Consume `{`
            let span = Span::new(start, self.peek().end);
            return AstNode::Invalid("Invalid macro rules definition!".to_string(), span);
        }
        let body = self.parse_block();
        let end = self.previous().end;
        let span = Span::new(start, end);
        AstNode::MacroRules(macro_name, Box::new(body), span)
    }


    fn check(&self, kind: TokenKind) -> bool {
        if self.at_end() {
            false
        } else {
            self.peek().kind == kind
        }
    }
    
    /// Skip whitespaces
    fn skip_whitespace(&mut self) {
        while self.peek().kind == TokenKind::Whitespace && !self.at_end() {
            self.advance();
        }
    }

    /// Skip comments
    fn skip_comment(&mut self) {
        match self.peek().kind {
            TokenKind::LineComment { doc_style } => {
                self.advance();
            },
            TokenKind::BlockComment { doc_style, terminated } => {
                self.advance();
            },
            _ => {
            
            },
        }
    }

    fn expect(&mut self, kind: TokenKind) {
        if self.peek().kind == kind {
            self.advance();
        } else {
            eprintln!("Expect {:?}, however provide {:?}", kind, self.peek());
            panic!();
        }
    }

    fn check_arrow(&mut self) -> bool {
        let current = self.peek();
        let next = self.peek_next();

        current.kind == TokenKind::Minus && next.kind == TokenKind::Gt
    }

    fn expect_arrow(&mut self) {
        if self.check_arrow() {
            self.advance(); // Consume `-`
            self.advance(); // Consume `>`
        } else {
            panic!("Expected '->' but found {:?}", self.peek().kind);
        }
    }

    fn peek_next(&self) -> &Token {
        if self.current + 1 >= self.tokens.len() {
            &self.tokens[self.tokens.len() - 1]
        } else {
            &self.tokens[self.current + 1]
        }
    }

    fn collect_until(&mut self, kind: TokenKind) -> String {
        let mut path = String::new();
        while self.peek().kind != kind && !self.at_end() {
            if self.check(TokenKind::Unknown) {
                return String::new();
            }
            path.push_str(&self.advance().to_string());
        }
        path
    }

    fn collect_paren_pair(&mut self) -> String {
        let mut path = String::new();
        let kind = TokenKind::CloseParen;
        while self.peek().kind != kind && !self.at_end() {
            if self.check(TokenKind::Unknown) {
                return String::new();
            }
            //println!("paren token: {:?}",self.peek());
            if self.check(TokenKind::OpenParen) {
                path.push_str(&self.advance().to_string());
                let nested_paren_path = self.collect_paren_pair();
                path.push_str(&nested_paren_path);
                //path.push_str(")");
                //self.advance(); // skip `)`
            }
            path.push_str(&self.advance().to_string());
        }
        path
    }

    fn collect_extern(&mut self) -> String {
        let mut path = String::new();
        while self.peek().kind != TokenKind::Semi && self.peek().kind != TokenKind::OpenBrace && 
            !self.at_end() {
            path.push_str(&self.advance().to_string());
        }
        if self.peek().kind == TokenKind::OpenBrace {
            self.parse_block();
        }
        path
    }

    fn collect_single_block(&mut self) -> String {
        let mut path = String::new();
        while self.peek().kind != TokenKind::Semi && !self.at_end() {
            path.push_str(&self.advance().to_string());
            if self.peek().kind == TokenKind::OpenBrace {
                self.parse_block();
            }
        }
        path
    }
    fn collect_statement(&mut self) -> String {
        let mut pairs = Vec::new();
        let mut path = String::new();
        loop {
            if self.at_end() {
                break;
            }
            match self.peek().kind {
                TokenKind::OpenBracket => {
                    pairs.push("[");
                    path.push_str("[");
                    self.advance();
                },
                TokenKind::CloseBracket => {
                    if pairs.is_empty() {
                        break;
                    }
                    pairs.pop();
                    path.push_str("]");
                    self.advance();
                },
                TokenKind::OpenParen => {
                    pairs.push("(");
                    path.push_str("(");
                    self.advance();
                },
                TokenKind::CloseParen => {
                    if pairs.is_empty() {
                        break;
                    }
                    pairs.pop();
                    path.push_str(")");
                    self.advance();
                },
                TokenKind::OpenBrace => {
                    pairs.push("{");
                    path.push_str("{");
                    self.advance();
                },
                TokenKind::CloseBrace => {
                    if pairs.is_empty() {
                        return path;
                    }
                    pairs.pop();
                    path.push_str("}");
                    self.advance();
                },
                TokenKind::Semi => {
                    if pairs.is_empty() {
                        if path.is_empty() {
                            path.push_str(" ");
                        }
                        break;
                    } else {
                        path.push_str(";");
                        self.advance();
                    }
                },
                TokenKind::Unknown => {
                    return String::new();
                },
                _ => {
                    path.push_str(&self.advance().to_string());  
                },
            }
        }
        path
    }

}
